<template>
    <!-- 顶部店铺信息 -->
    <view class="shops">
        <view class="flex1">
            <image class="flex1-img" :src="sidebar.shop?.logo" mode=""></image>
            <view class="flex-right">
                <view>{{ sidebar.shop.name }}</view>
                <view class="text">距离{{ sidebar.shop.distance_text }}</view>
            </view>
        </view>
        <image @click="ngn" class="area" src="@/static/positioning.png" mode=""></image>
    </view>
    <!-- 侧边栏 -->
    <view class="wraper">
        <wd-sidebar v-model="active" @change="handleChange">
            <wd-sidebar-item v-for="(item, index) in categories" :key="index" :value="index" :label="item" />
        </wd-sidebar>
        <view class="content">
            <scroll-view class="category" scroll-y scroll-with-animation :show-scrollbar="false" :scroll-top="scrollTop" :throttle="false">
                <view style="padding-bottom: 200rpx">
                    <view v-if="load" class="box1" v-for="it in rightContent" :key="(it, id)" @click="shopDetas2(it)">
                        <image class="box1-img" :src="it.image" mode="aspectFit"></image>
                        <view class="box-a">
                            <view class="box-1">{{ it.title }}</view>
                            <view class="txt txt1">{{ it.goods_sku_text }}</view>
                            <view class="txt">月售 {{ it.sales }}</view>
                            <view class="box-btm">
                                <view class="price">￥{{ it.price }}</view>
                                <view class="diaply">
                                    <!-- <image class="jia1" src="@/static/jian.png" mode=""></image> -->
                                    <image @click.stop="jian(it)" v-if="it.goods_num !== 0" class="jia1" src="@/static/jian.png" mode=""></image>
                                    <!-- <view class="prictet"> -->
                                    <view class="prictet" v-if="it.goods_num !== 0">
                                        {{ it.goods_num }}
                                    </view>
                                    <image @click.stop="add(it)" class="jia1" src="@/static/jia1.png" mode=""></image>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
    </view>
    <view class="fotter">
        <view>
            合计
            <text class="txt">￥{{ Math.max(totalPrice, 0).toFixed(2) }}</text>
        </view>
        <view class="btn" @click="watBtn">去支付</view>
    </view>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { goodstore, getGoodsList, getCreate, user } from '@/api/index.js';
import { utils } from '@/utils/utils.js';
import { onLoad, onShow } from '@dcloudio/uni-app';
const active = ref(0); //侧边栏默认位置
const scrollTop = ref(0);
const categories = ref([]); //左侧显示的信息
const ids = ref(''); //店铺id获取店铺
const sidebar = ref({}); //店铺信息与左侧侧边栏
const rightContent = ref([]); //右边内容
const load = ref(1); //0隐藏1显示，数据加载失败隐藏右侧内容
const totalPrice = ref(0); //合计价格
const strog = ref([]); //存储数量
const userProfile = ref({}); //存储用户信息
const create = ref({
    list: [
        {
            shop_id: '',
            remark: '',
            goods_list: []
        }
    ],
    // voucher: '' //代金券
});
onLoad((options) => {
    if (options.ids) {
        ids.value = options.ids;
    }
    assortList(); // 获取店铺信息与左侧侧边栏
    userInfo(); //获取用户信息
});
// 点击去支付
const watBtn = async () => {
    strog.value = strog.value.map((item) => ({
        ...item, // 复制当前对象
        goods_sku_price_id: item.id
    }));
    create.value.list[0].shop_id = ids.value;
    create.value.list[0].goods_list.push(...strog.value);
    const ret = await getCreate(JSON.stringify(create.value));
    if (ret.code == 1) {
        // =创建订单成功跳转待支付页面
        uni.redirectTo({
            url: `/pages/sub/daipayment?id=${ret.data[0].id}`
        });
    } else {
        utils(ret.msg);
    }
};
// 点击加号判断对象有没有相同数据
const add = (it) => {
    console.log('加', it);
    it.goods_num++;
    const match = strog.value.find((sItem) => sItem.id === it.id);
    if (match) {
        match.goods_num++;
    } else {
        strog.value.push({ ...it });
        // match.goods_num++;
    }
    if (it.goods_num != 1) {
        const newp = Number(it.price) + Number(it.newPrice);
        it.price = newp.toFixed(2);
        match.price = newp.toFixed(2);
    }
    totalPrice.value += Number(it.newPrice);
    console.log();
    console.log('存储的数据', strog.value);
};
// 点击减号
const jian = (it) => {
    it.goods_num--;
    const match = strog.value.find((sItem) => sItem.id === it.id);
    if (match) {
        match.goods_num--;
        if (match.goods_num == 0) {
            // 当前商品减到0就移除当前商品
            strog.value = strog.value.filter((sItem) => sItem.id !== match.id);
        }
        console.log('有相同的数据', strog.value);
    }
    if (it.goods_num != 0) {
        const newp = Number(it.price) - Number(it.newPrice);
        it.price = newp.toFixed(2);
        match.price = newp.toFixed(2);
    }
    totalPrice.value -= Number(it.newPrice);
};
// 获取店铺信息与左侧侧边栏
const assortList = async () => {
    console.log(rightContent.value);
    rightContent.value = [];
    const ret = await goodstore(ids.value);
    console.log(ret);
    if (ret.code == 1) {
        sidebar.value = ret.data; //店铺信息
        categories.value = ret.data.category.map((category) => category.name); //提取name字段在左侧显示
        // 默认显示第一个左侧内容
        const res = await getGoodsList(sidebar.value.category[0].shop_id, sidebar.value.category[0].id);
        if (res.code == 1) {
            res.data.forEach((item) => {
                // 遍历sku_prices数组
                item.sku_prices.forEach((sku) => {
                    // 复制title和image到sku对象中
                    sku.title = item.title;
                    sku.image = item.image;
                    // 添加goods_num属性并设置为0
                    sku.goods_num = 0;
                    sku.newPrice = item.price;
                    // 将sku对象添加到新数组中
                    rightContent.value.push(sku);
                });
            });
            load.value = 1;
        } else {
            utils(res.msg);
            load.value = 0;
        }
    }
};
// 切换侧边栏
async function handleChange({ label }) {
    rightContent.value = [];
    // 切换侧边栏
    const matchedItem = sidebar.value.category.find((item) => {
        return item.name === label;
    });
    console.log(active.value);
    if (matchedItem) {
        const ret = await getGoodsList(matchedItem.shop_id, matchedItem.id);
        if (ret.code == 1) {
            ret.data.forEach((item) => {
                // 遍历sku_prices数组
                item.sku_prices.forEach((sku) => {
                    // 复制title和image到sku对象中
                    sku.title = item.title;
                    sku.image = item.image;
                    // 添加goods_num属性并设置为0
                    sku.goods_num = 0;
                    sku.newPrice = item.price;
                    // 将sku对象添加到新数组中
                    rightContent.value.push(sku);
                });
            });
            load.value = 1;
            console.log(44, rightContent.value);
        } else {
            utils(ret.msg);
            load.value = 0;
        }
    } else {
        utils();
    }

    // 获取之前存储历史
    // 创建一个映射对象，用于快速查找 strog 数组中的 goods_num 值
    const strogMap = {};
    strog.value.forEach((item) => {
        strogMap[item.id] = item.goods_num;
    });
    // 遍历 rightContent 数组，更新对象
    rightContent.value.forEach((item) => {
        if (strogMap.hasOwnProperty(item.id)) {
            // 如果 strogMap 中存在对应的 id，则更新 rightContent 数组中对象的 goods_num 属性
            item.goods_num = strogMap[item.id];
            item.price = Number(item.goods_num) * Number(item.newPrice);
        }
    });
}

//点击商品跳转商品详情
const shopDetas2 = (it) => {
    console.log(it);
    uni.navigateTo({
        url: `/pages/sub/shopDetails?ids=${it.goods_id}`
    });
};
// 获取用户信息
const userInfo = async () => {
    const ret = await user();
    if (ret.code == 1) {
        userProfile.value = ret.data;
        console.log('个人信息', userProfile.value);
        // create.value.voucher = ret.data.voucher;
    } else {
        utils('数据加载失败！');
    }
};
const ngn = () => {
    uni.openLocation({
        latitude: Number(sidebar.value.shop.lat),
        longitude: Number(sidebar.value.shop.lng),
        success: function () {
            console.log('success');
        }
    });
};
</script>

<style lang="scss" scoped>
::v-deep .wd-sidebar-item--active {
    color: #000 !important;
}
::v-deep .wd-sidebar-item--active::before {
    content: none !important;
}
// 底部价格
.fotter {
    .txt {
        color: #fd5536;
    }
    .btn {
        width: 200rpx;
        height: 88rpx;
        background: #f8bb4f;
        line-height: 88rpx;
        text-align: center;
        border-radius: 50rpx;
        color: #fff;
    }
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 120rpx;
    width: 100%;
    background-color: #fff;
    position: fixed;
    bottom: 0;
    padding: 16rpx 24rpx 16rpx 34rpx;
    z-index: 999;
}
// 顶部店铺
.shops {
    .flex1 {
        .flex-right {
            .text {
                color: #999999;
                font-size: 25rpx;
                margin-top: 20rpx;
            }
        }
        .flex1-img {
            width: 108rpx;
            height: 108rpx;
            border-radius: 30rpx;
            margin-right: 26rpx;
        }
        display: flex;
        align-items: center;
    }
    .area {
        width: 56rpx;
        height: 56rpx;
    }
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 40rpx;
    height: 180rpx;
    position: fixed;
    width: 100%;
    top: 0;
    border-bottom: 2rpx solid #f5f5f5;
}
.wraper {
    .content {
        flex: 1;
        background: #fff;
        .category {
            .box1 {
                .box-a {
                    .box-1 {
                        white-space: nowrap; /* 禁止换行 */
                        overflow: hidden; /* 隐藏超出部分 */
                        width: 250rpx;
                        text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
                    }
                    .txt1 {
                        margin: 10rpx 0;
                    }
                    .txt {
                        color: #999999;
                        font-size: 25rpx;
                        // margin-top: 20rpx;
                        margin-bottom: 5rpx;
                    }
                    .box-btm {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;
                        .diaply {
                            display: flex;
                            justify-content: space-between;
                            align-items: center;
                        }
                        .prictet {
                            margin: 0 10rpx;
                        }
                        .jia1 {
                            width: 32rpx;
                            height: 32rpx;
                        }
                        .price {
                            color: #f84834;
                        }
                    }
                }
                .box1-img {
                    width: 150rpx;
                    height: 116rpx;
                    margin-right: 52rpx;
                }
                padding: 58rpx 40rpx 0 58rpx;
                display: flex;
                align-items: center;
                // justify-content: space-between;
            }
            box-sizing: border-box;
            height: 100%;
        }
    }
    display: flex;
    height: calc(100vh - var(--window-top));
    height: calc(100vh - var(--window-top) - constant(safe-area-inset-bottom));
    height: calc(100vh - var(--window-top) - env(safe-area-inset-bottom));
    overflow: hidden;
    padding-top: 180rpx;
    padding-bottom: 110rpx;
}
</style>
